package com.hwy.widget.decoration

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.annotation.IntRange
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/3/8 0:08
 * 说明: RecyclerView 常规使用的 ItemDecoration
 * =======================================
 */
class CommonDecoration(
    private val context: Context,
    @IntRange(from = 0) var itemSpan: Int,
    var drawable: Drawable?
) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {

        // parent.getChildLayoutPosition() 获取 View 的位置有延迟
        val position = parent.getChildAdapterPosition(view)
        // parent.getChildAdapterPosition() 获取数据没有延迟，有可能出现 -1 的情况，需要处理
        if (position == RecyclerView.NO_POSITION) {
            return
        }

        var left = 0
        var top = 0
        var right = 0
        var bottom = itemSpan
        parent.layoutManager?.run {
            when (this) {
                is GridLayoutManager -> {
                    val column = spanCount
                    left += if (position % column == 0) {
                        paddingLeft
                    } else {
                        itemSpan / 2
                    }
                    right = if ((position + 1) % column == 0) {
                        paddingRight
                    } else {
                        itemSpan / 2
                    }
                }
                is LinearLayoutManager -> {
                    left = paddingLeft
                    right = paddingRight
                }
            }
        }
        outRect.set(left, top, right, bottom)

    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
    }

}